package com.xmut.xmutbackend.controller;

import com.xmut.xmutbackend.entity.Result;
import com.xmut.xmutbackend.entity.Users;
import com.xmut.xmutbackend.service.IUsersService;
import com.xmut.xmutbackend.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@CrossOrigin // 添加跨域支持
public class LoginController {

    @Autowired
    private IUsersService usersService;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Users users) {
        try {
            // 记录请求日志
            System.out.println("接收到登录请求，用户名: " + users.getUsername());
            System.out.println("密码长度: " + (users.getPassword() != null ? users.getPassword().length() : 0));
            
            Users user = usersService.login(users.getUsername(), users.getPassword());
            if (user != null) {
                try {
                    // 使用JWT生成令牌
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("id", user.getId());
                    claims.put("username", user.getUsername());
                    String token = JwtUtils.generateJwt(claims);
                    
                    // 更新用户表中的Token字段
                    user.setToken(token);
                    usersService.updateById(user);
                    
                    // 返回用户信息和token
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("token", token); // 确保这是单纯的字符串，非对象
                    resultMap.put("userId", user.getId());
                    resultMap.put("username", user.getUsername());
                    resultMap.put("avatar", user.getAvatar() != null ? user.getAvatar() : "");
                    
                    System.out.println("登录成功，用户名: " + user.getUsername() + ", token长度: " + token.length());
                    return Result.success(resultMap);
                } catch (Exception e) {
                    System.out.println("生成JWT令牌异常: " + e.getMessage());
                    e.printStackTrace();
                    return Result.fail("服务器内部错误: JWT生成失败");
                }
            } else {
                System.out.println("登录失败，用户名或密码错误: " + users.getUsername());
                return Result.fail("用户名或密码错误");
            }
        } catch (Exception e) {
            System.out.println("登录过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.fail("服务器内部错误: " + e.getMessage());
        }
    }
    
    @GetMapping("/info")
    public Result<Users> getUserInfo(@RequestParam(required = false) String token) {
        try {
            // 从请求头中获取token，这里的token参数保留只是为了兼容
            if (token == null || token.isEmpty()) {
                return Result.fail("未提供有效的token");
            }
            
            System.out.println("获取用户信息，token: " + token.substring(0, Math.min(10, token.length())) + "...");
            
            // 解析token获取用户ID
            Map<String, Object> claims = JwtUtils.parseJWTToMap(token);
            if (claims.isEmpty()) {
                return Result.fail("无效的token");
            }
            
            Integer userId = Integer.parseInt(claims.get("id").toString());
            System.out.println("解析到的用户ID: " + userId);
            
            // 查询用户信息
            Users user = usersService.getById(userId);
            if(user != null) {
                user.setPassword(null); // 清除密码敏感信息
                return Result.success(user);
            }
            return Result.fail("用户不存在");
        } catch (Exception e) {
            System.out.println("获取用户信息异常: " + e.getMessage());
            e.printStackTrace();
            return Result.fail("获取用户信息失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/logout")
    public Result<String> logout() {
        // JWT本身是无状态的，服务端不需要做特殊处理
        // 实际的登出操作由客户端删除token完成
        return Result.success("退出成功");
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody Users user) {
        System.out.println("接收到注册请求，用户名: " + user.getUsername());
        
        // 检查必填字段
        if (user.getUsername() == null || user.getPassword() == null || user.getEmail() == null) {
            return Result.fail("用户名、密码和邮箱不能为空");
        }
        
        // 检查用户名是否已存在
        if (usersService.checkUsernameExists(user.getUsername())) {
            return Result.fail("用户名已存在，请更换其他用户名");
        }
        
        // 注册用户
        boolean success = usersService.register(user);
        if (success) {
            System.out.println("注册成功，用户名: " + user.getUsername());
            return Result.success("注册成功");
        } else {
            System.out.println("注册失败，用户名: " + user.getUsername());
            return Result.fail("注册失败，请稍后再试");
        }
    }
    
    /**
     * 验证用户名和邮箱
     */
    @PostMapping("/verify")
    public Result<String> verifyUserEmail(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String email = params.get("email");
        
        System.out.println("接收到验证请求，用户名: " + username);
        
        if (username == null || email == null) {
            return Result.fail("用户名和邮箱不能为空");
        }
        
        boolean verified = usersService.verifyUserEmail(username, email);
        if (verified) {
            System.out.println("验证成功，用户名: " + username);
            return Result.success("验证成功");
        } else {
            System.out.println("验证失败，用户名: " + username);
            return Result.fail("用户名和邮箱不匹配");
        }
    }
    
    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public Result<String> resetPassword(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String newPassword = params.get("newPassword");
        
        System.out.println("接收到密码重置请求，用户名: " + username);
        
        if (username == null || newPassword == null) {
            return Result.fail("用户名和新密码不能为空");
        }
        
        boolean updated = usersService.updatePassword(username, newPassword);
        if (updated) {
            System.out.println("密码重置成功，用户名: " + username);
            return Result.success("密码重置成功");
        } else {
            System.out.println("密码重置失败，用户名: " + username);
            return Result.fail("密码重置失败，请稍后再试");
        }
    }
    
    // 添加测试接口
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("登录接口正常");
    }
}
